using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Admin3000.Backend.Api.Database;
using Microsoft.EntityFrameworkCore;
using Admin3000.Backend.Api.Repository;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Admin3000.Backend.Api.Params;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using Admin3000.Backend.Api.Filters;

namespace Admin3000.Backend.Api
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // 注入数据库上下文
            services.AddDbContext<Admin3000Db>(o => o.UseSqlServer());

            // 注入 IRepository接口及其实现类
            services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));

            // 配置token验证的设置
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata = false;
                options.SaveToken = true;
                var tokenParameter = Configuration.GetSection("TokenParameter").Get<TokenParameter>();
                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenParameter.Secret)),
                    ValidateIssuer = true,
                    ValidIssuer = tokenParameter.Issuer,
                    ValidateAudience = false
                };

            });


            services.AddControllers(options=>
            {
                options.Filters.Add(typeof(AuditLogActionFilter));
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }


            app.UseRouting();

            // 注册验证token的中间件
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
